import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../tools/shared_preferences_tool.dart';
import 'theme_data.dart';

/// 主题管理器
/// 负责管理应用的主题切换和持久化存储
class ThemeManager extends GetxController {
  static ThemeManager get instance => Get.find<ThemeManager>();

  /// 当前主题模式
  final Rx<ThemeMode> _themeMode = ThemeMode.system.obs;
  ThemeMode get themeMode => _themeMode.value;

  /// 是否为暗黑模式
  final RxBool _isDarkMode = false.obs;
  bool get isDarkMode => _isDarkMode.value;

  /// 主题颜色
  final Rx<Color> _primaryColor = const Color(0xFF4A90E2).obs;
  Color get primaryColor => _primaryColor.value;

  /// 可选的主题颜色列表
  final List<Color> availableColors = [
    const Color(0xFF4A90E2), // 蓝色
    const Color(0xFF2ECC71), // 绿色
    const Color(0xFFE74C3C), // 红色
    const Color(0xFFF39C12), // 橙色
    const Color(0xFF9B59B6), // 紫色
    const Color(0xFF1ABC9C), // 青色
    const Color(0xFFE67E22), // 深橙色
    const Color(0xFF34495E), // 深蓝灰色
  ];

  @override
  void onInit() {
    super.onInit();
    _loadThemeSettings();
    _listenToSystemTheme();
  }

  /// 加载主题设置
  Future<void> _loadThemeSettings() async {
    try {
      // 加载主题模式
      final themeModeIndex = SharedPreferencesTool.getInt('theme_mode') ?? 0;
      _themeMode.value = ThemeMode.values[themeModeIndex];

      // 加载暗黑模式设置
      final isDark = SharedPreferencesTool.getBool('is_dark_mode') ?? false;
      _isDarkMode.value = isDark;

      // 加载主题颜色
      final colorValue = SharedPreferencesTool.getInt('primary_color');
      if (colorValue != null) {
        _primaryColor.value = Color(colorValue);
      }

      // 应用主题
      _applyTheme();
    } catch (e) {
      debugPrint('加载主题设置失败: $e');
    }
  }

  /// 监听系统主题变化
  void _listenToSystemTheme() {
    // 监听系统主题变化
    ever(_themeMode, (ThemeMode mode) {
      if (mode == ThemeMode.system) {
        final brightness =
            WidgetsBinding.instance.platformDispatcher.platformBrightness;
        _isDarkMode.value = brightness == Brightness.dark;
      }
    });
  }

  /// 切换主题模式
  Future<void> setThemeMode(ThemeMode mode) async {
    try {
      _themeMode.value = mode;
      await SharedPreferencesTool.putInt('theme_mode', mode.index);

      // 根据主题模式更新暗黑模式状态
      if (mode == ThemeMode.light) {
        _isDarkMode.value = false;
      } else if (mode == ThemeMode.dark) {
        _isDarkMode.value = true;
      } else {
        // 系统模式，根据系统设置
        final brightness =
            WidgetsBinding.instance.platformDispatcher.platformBrightness;
        _isDarkMode.value = brightness == Brightness.dark;
      }

      await SharedPreferencesTool.putBool('is_dark_mode', _isDarkMode.value);
      _applyTheme();
    } catch (e) {
      debugPrint('设置主题模式失败: $e');
    }
  }

  /// 切换暗黑模式
  Future<void> toggleDarkMode() async {
    try {
      _isDarkMode.value = !_isDarkMode.value;
      _themeMode.value = _isDarkMode.value ? ThemeMode.dark : ThemeMode.light;

      await SharedPreferencesTool.putBool('is_dark_mode', _isDarkMode.value);
      await SharedPreferencesTool.putInt('theme_mode', _themeMode.value.index);

      _applyTheme();
    } catch (e) {
      debugPrint('切换暗黑模式失败: $e');
    }
  }

  /// 设置主题颜色
  Future<void> setPrimaryColor(Color color) async {
    try {
      _primaryColor.value = color;
      await SharedPreferencesTool.putInt('primary_color', color.value);
      _applyTheme();
    } catch (e) {
      debugPrint('设置主题颜色失败: $e');
    }
  }

  /// 应用主题
  void _applyTheme() {
    Get.changeThemeMode(_themeMode.value);
  }

  /// 获取当前主题数据
  ThemeData get lightTheme {
    return themeDataLight.copyWith(
      primaryColor: _primaryColor.value,
      colorScheme: themeDataLight.colorScheme.copyWith(
        primary: _primaryColor.value,
      ),
    );
  }

  /// 获取暗黑主题数据
  ThemeData get darkTheme {
    return themeDataDark.copyWith(
      primaryColor: _primaryColor.value,
      colorScheme: themeDataDark.colorScheme.copyWith(
        primary: _primaryColor.value,
      ),
    );
  }

  /// 获取主题模式名称
  String getThemeModeName(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.light:
        return '浅色模式';
      case ThemeMode.dark:
        return '深色模式';
      case ThemeMode.system:
        return '跟随系统';
    }
  }

  /// 获取颜色名称
  String getColorName(Color color) {
    if (color.value == const Color(0xFF4A90E2).value) return '蓝色';
    if (color.value == const Color(0xFF2ECC71).value) return '绿色';
    if (color.value == const Color(0xFFE74C3C).value) return '红色';
    if (color.value == const Color(0xFFF39C12).value) return '橙色';
    if (color.value == const Color(0xFF9B59B6).value) return '紫色';
    if (color.value == const Color(0xFF1ABC9C).value) return '青色';
    if (color.value == const Color(0xFFE67E22).value) return '深橙色';
    if (color.value == const Color(0xFF34495E).value) return '深蓝灰色';
    return '自定义';
  }

  /// 重置主题设置
  Future<void> resetTheme() async {
    try {
      await SharedPreferencesTool.remove('theme_mode');
      await SharedPreferencesTool.remove('is_dark_mode');
      await SharedPreferencesTool.remove('primary_color');

      _themeMode.value = ThemeMode.system;
      _isDarkMode.value = false;
      _primaryColor.value = const Color(0xFF4A90E2);

      _applyTheme();
    } catch (e) {
      debugPrint('重置主题设置失败: $e');
    }
  }

  /// 获取当前主题的对比色
  Color get contrastColor {
    return _isDarkMode.value ? Colors.white : Colors.black;
  }

  /// 获取当前主题的背景色
  Color get backgroundColor {
    return _isDarkMode.value ? const Color(0xFF121212) : Colors.white;
  }

  /// 获取当前主题的卡片颜色
  Color get cardColor {
    return _isDarkMode.value ? const Color(0xFF1E1E1E) : Colors.white;
  }

  /// 获取当前主题的分割线颜色
  Color get dividerColor {
    return _isDarkMode.value ? Colors.grey[800]! : Colors.grey[300]!;
  }
}
